<?php
/*
 * 上传管理
 */
namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\facade\Session;
use think\facade\Db;
use think\facade\Filesystem;
use app\common\model\System;
use OSS\OssClient;
use OSS\Core\OssException;

class Uploads extends AdminBase
{
    protected $noAuth = [ 'uploadImage', 'uploadFile', 'uploadVideo'];

    public function lists()
    {
        $list = Db::table('uploads')->order('id desc')->paginate();
        return $this->fetch('index',['list'=>$list]);
    }

    //上传图片
    public function uploadImage()
    {
        $file = $this->request->file('file');
        try{
            validate(['file'=>[
                'fileSize' => 20 * 1024 * 1024,  //单图最大上传20M
                'fileExt' => 'jpg,jpeg,png,bmp,gif',
                'fileMime' => 'image/jpeg,image/jpg,image/png,image/gif', //这个一定要加上，很重要我认为！
            ]])->check(['file' => $file]);
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $format = $file->getOriginalExtension();//原始后缀
        $oss_config = System::get_config_by_code('oss');
        if ($oss_config['is_oss']) {//开启OSS存储
            // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录https://ram.console.aliyun.com创建RAM账号。
            $accessKeyId = $oss_config['oss_ak'];
            $accessKeySecret = $oss_config['oss_sk'];
            // Endpoint以杭州为例，其它Region请按实际情况填写。
            $endpoint = $oss_config['oss_endpoint'];
            // 存储空间名称
            $bucket = $oss_config['oss_bucket'];
            // 设置文件名称。
            $filename = sha1(date('YmdHis', time()) . uniqid()).'.'. $format;
            // <yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
            $filePath = $file->getRealPath();

            try {
                $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
                $result = $ossClient->uploadFile($bucket, $filename, $filePath);
                if(!$result){
                    $this->error('上传失败');
                }
                $url = $result['info']['url'];

            } catch (OssException $e) {
                print $e->getMessage();
            }

        }else{//本地存储
            //判断上传位置
            $savename = Filesystem::disk('public')->putFile('uploads',$file);
            //$url = request()->domain().'/'.$savename;//带域名目录
            $url = '/'.str_replace('\\', '/', $savename);
            $filename = substr($file->hashName(),9);
        }
        Db::table('uploads')->insert([
            'model'         => session('admin_auth.user_name'),
            'type'          => $oss_config['is_oss'],
            'user_id'       => md6(AdminId(),true),
            'filename'      => $filename,
            'filesize'      => $file->getSize(),
            'mine'          => $file->getOriginalMime(),
            'create_time'   => time(),
            'url'           => $url
        ]);

        insert_admin_log('上传了图片');
        $this->success('上传成功',$url);
    }
    //删除图片
    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $files = Db::table('uploads')->find($param['id']);
            //判断存储位置
            if($files['type']){
                $oss_config = System::get_config_by_code('oss');
                // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录https://ram.console.aliyun.com创建RAM账号。
                $accessKeyId = $oss_config['oss_ak'];
                $accessKeySecret = $oss_config['oss_sk'];
                // Endpoint以杭州为例，其它Region请按实际情况填写。
                $endpoint = $oss_config['oss_endpoint'];
                // 存储空间名称
                $bucket = $oss_config['oss_bucket'];
                $endpoint = $oss_config['oss_endpoint'];
                $object = $files['filename'];
                try {
                    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
                    $ossClient->deleteObject($bucket, $object);

                } catch (OssException $e) {
                    print $e->getMessage();
                }
                Db::table('uploads')->where('id',$param['id'])->delete();
                insert_admin_log('删除了图片');
                $this->success('删除成功');
            }else{
                if(file_exists('.'.$files['url'])){
                    unlink('.'.$files['url']);//删除本地文件
                }
                Db::table('uploads')->where('id',$param['id'])->delete();
                insert_admin_log('删除了图片');
                $this->success('删除成功');
            }
        }
    }

}
